package com.framework2.utils;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ListAdapter;

import com.framework.Utils.ScreenUtils;

/**
 * @author 动态设置gridView的高度
 *         className GridViewUtil
 *         created at  2017/3/20  17:36
 */
public class GridViewUtil {
    private static volatile GridViewUtil singleton;

    private GridViewUtil() {
    }

    public static GridViewUtil getInstance() {
        if (singleton == null) {
            synchronized (GridViewUtil.class) {
                if (singleton == null) {
                    singleton = new GridViewUtil();
                }
            }
        }
        return singleton;
    }

    /**
     * 动态设置gridView的高度
     *
     * @param context  上下文
     * @param gridView 被设置高度的gridView
     */
    public void setListViewHeightBasedOnChildren(Context context, GridView gridView,int itemHeithtDp, boolean noMargin) {
        // 获取listview的adapter
        ListAdapter listAdapter = gridView.getAdapter();
        if (listAdapter == null)
            return;
        // / 固定列宽，有多少列
        int col = 3;
        //		 listView.getNumColumns();
        int totalHeight = 0;
        // i每次加4，相当于listAdapter.getCount()小于等于4时 循环一次，计算一次item的高度，
        // listAdapter.getCount()小于等于8时计算两次高度相加
        for (int i = 0; i < listAdapter.getCount(); i += col) {
            // 获取listview的每一个item
            View listItem = listAdapter.getView(i, null, gridView);
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += ScreenUtils.getInstance().dip2px(context, itemHeithtDp);
        }
        // 获取listview的布局参数
        ViewGroup.LayoutParams params = gridView.getLayoutParams();
        // 设置高度
        params.height = totalHeight;
        // 设置margin
        ((ViewGroup.MarginLayoutParams) params).setMargins(noMargin ? 0 : ScreenUtils.getInstance().dip2px(context,12), 0, noMargin ? 0 : ScreenUtils.getInstance().dip2px(context,12), 0);
        // 设置参数
        gridView.setLayoutParams(params);
    }

    public void setListViewHeightBasedOnChildren(Context context, GridView gridView,int itemHeithtDp) {
        setListViewHeightBasedOnChildren(context, gridView,itemHeithtDp, false);
    }
}
